#include "Heap.h"


void HPInit(HP* php)
{
	assert(php);
	php->arr = NULL;
	php->capacity = php->size = 0;
}

void Swap(HPDataType* x, HPDataType* y)
{
	HPDataType tmp = *x;
	*x = *y;
	*y = tmp;
}

void AdjustUp(HPDataType* arr, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child] < arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			return;
		}
	}
}


void HPPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->capacity == php->size)
	{
		int newcapcity = php->capacity == 0 ? 4 : 2 * php->capacity;
		HPDataType* tmp = (HPDataType*)realloc(php->arr, sizeof(HPDataType) * newcapcity);
		if (tmp==NULL)
		{
			perror("realloc error!");
			exit(1);
		}
		php->capacity = newcapcity;
		php->arr = tmp;
	}
	php->arr[php->size] = x;
	AdjustUp(php->arr,php->size);
	++php->size;

}


bool HPEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}


HPDataType HPTop(HP* php)
{
	assert(php && php->size);
	return php->arr[0];
}

void AdjustDown(HPDataType* arr, int parent, int n)
{
	int child = (parent * 2) + 1;
	while (child < n)
	{
		if (child + 1 < n && arr[child] > arr[child + 1])
		{
			child++;
		}
		if (arr[child]<arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			parent = child;
			child = (parent * 2) + 1;
		}
		else
		{
			return;
		}
	}
}

void HPPop(HP* php)
{
	assert(php && php->size);
	Swap(&php->arr[0], &php->arr[php->size - 1]);
	php->size--;
	AdjustDown(php->arr,0,php->size);
}